# -*- coding: utf-8 -*-
import re
import datetime
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.db.models.signals import post_save
from django.dispatch.dispatcher import receiver
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.context import RequestContext, Context
from WebSite.forms import userForm
from WebSite.models import News, Doubts, QuizHelper, Quiz, QuestionHelper, Question, UserProfile
from django import forms
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

__author__ = 'Nataliel Vasconcelos'

def homepage(request):
    news = News.objects.filter(publish__exact='True',detach__exact='True').order_by('-date')[:3]
    return render_to_response('Website/index.html',locals(),context_instance = RequestContext(request))

def doubts(request):
    doubts = Doubts.objects.filter(publish__exact='True').order_by('-date')[:10]
    if request.method == 'POST':
        form = FormContact(request.POST)

        if form.is_valid():
            form.enviar()
            mostrar = 'Contato enviado!'
            form = FormContact()
    else:
        form = FormContact()
    return render_to_response('Website/duvidas.html',locals(),context_instance = RequestContext(request))

def news(request):
    news = News.objects.filter(publish__exact='True').order_by('-date')
    page = request.GET.get('page')
    if not page:
        page = 1
    paginator = Paginator( news , 5 )

    try:
        paginated_news = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        paginated_news = paginator.page(1)
        page = 1
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        paginated_news = paginator.page(paginator.num_pages)
        page = paginator.num_pages

    next_page = int( page ) + 1
    previous_page = int( page ) - 1
    return render_to_response('Website/noticias.html',locals(),context_instance = RequestContext(request))

def newsIntern(request, slugNews):
    newsAll = News.objects.filter(publish__exact='True').order_by('-date')
    news = News.objects.get(slugNews = slugNews)
    return render_to_response('Website/noticia-interna.html',locals(),context_instance = RequestContext(request))

def about(request):
    return render_to_response('Website/sobre.html',locals(),context_instance = RequestContext(request))

def spellingBook(request):
    return render_to_response('Website/cartilha.html',locals(),context_instance = RequestContext(request))
@login_required
def quizPainel(request):
    profile = UserProfile.objects.filter( user = request.user  )[0]

    answered_quizes = QuizHelper.objects.filter( user = request.user )
    new_quizes = Quiz.objects.exclude( id__in = answered_quizes.values( "quiz_id" ) )

    quizes_time = datetime.timedelta( microseconds = profile.totalTime )
    questions_count = profile.reponseQuiz
    corrected_answers_count = profile.valueCorrect
    total_points = profile.pointsQuiz

    total_time = '00:00:00'
    seconds = quizes_time.seconds
    hours = seconds // 3600
    seconds = seconds - hours * 3600
    minutes = seconds // 60
    seconds = seconds - ( minutes * 60 )
    total_time = '%02d:%02d:%02d' % (hours, minutes, seconds)

    page = request.GET.get('page')
    if not page:
        page = 1
    paginator = Paginator( answered_quizes , 5 )

    try:
        paginated_answered_quizes = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        paginated_answered_quizes = paginator.page(1)
        page = 1
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        paginated_answered_quizes = paginator.page(paginator.num_pages)
        page = paginator.num_pages

    next_page = int( page ) + 1
    previous_page = int( page ) - 1

    ranking_users = UserProfile.objects.order_by( '-pointsQuiz', 'totalTime' , '-valueCorrect' )[:5]

    return render_to_response('Website/quiz-painel.html',locals(),context_instance = RequestContext(request))
@login_required
def quizFinal(request, quiz_id ):
    quiz = Quiz.objects.get( id = quiz_id )

    helpers = QuizHelper.objects.filter( user = request.user , quiz = quiz )
    if helpers.count() > 0 :
        raise Exception( "O quiz informado já foi respondido" )

    profile = UserProfile.objects.filter( user = request.user  )[0]
    profile.valueQuiz = profile.valueQuiz + 1

    helper = QuizHelper( user = request.user, quiz = quiz, start_time = datetime.datetime.fromtimestamp( float( request.POST.get( 'start_time' ) ) ) )
    helper.end_time = datetime.datetime.now()

    duration = helper.end_time - helper.start_time
    duration_in_float = duration.microseconds + ( duration.seconds + duration.days * 86400 ) * 1000000

    helper.duration = duration_in_float
    helper.save()

    correct_answers_amount = 0
    for parameter in request.POST.keys():
        regex = re.compile( 'question(\d+)' )
        matcher = regex.match( parameter )
        if matcher :
            question = Question.objects.get( id = matcher.group( 1 ) )
            user_answer = request.POST.get( parameter )
            if question.correct_answer == user_answer :
                correct_answers_amount += 1
                helper.points += question.weight
            QuestionHelper( quiz_helper = helper, question = question, user_answer = user_answer ).save()

    helper.correct_answers = correct_answers_amount
    helper.save()

    profile.pointsQuiz = profile.pointsQuiz + helper.points
    profile.valueCorrect = profile.valueCorrect + helper.correct_answers
    profile.reponseQuiz = profile.reponseQuiz + helper.quiz.question_set.count()
    profile.totalTime = profile.totalTime + duration_in_float

    profile.save()

    seconds = duration.seconds

    hours = seconds // 3600
    seconds = seconds - hours * 3600

    minutes = seconds // 60
    seconds = seconds - ( minutes * 60 )

    total_time = '%02d:%02d:%02d' % (hours, minutes, seconds)

    return render_to_response('Website/quiz-final.html',locals(),context_instance = RequestContext(request))


def quizLogin(request):
    return render_to_response('Website/quiz-login.html',locals(),context_instance = RequestContext(request))

def quizPerguntas(request, quiz_id ):
    quiz = Quiz.objects.get( id = quiz_id )
    return render_to_response('Website/quiz-perguntas.html',locals(),context_instance = RequestContext(request))

class FormContact(forms.Form):
    nome = forms.CharField(max_length=50)
    email = forms.EmailField(label = ('E-mail'),required=False)
    mensagem = forms.Field(widget=forms.Textarea)

    def enviar(self):
        titulo = 'Mensagem enviada pelo site'
        destino = ''
        texto = """
        Nome: %(nome)s
        E-mail: %(email)s
        Mensagem: %(mensagem)s
        """ % self.cleaned_data

        send_mail(
            subject=titulo,
            message=texto,
            from_email=destino,
            recipient_list=[destino],
        )

def contact(request):
    if request.method == 'POST':
        form = FormContact(request.POST)

        if form.is_valid():
            form.enviar()
            mostrar = 'Contato enviado!'
            form = FormContact()
    else:
        form = FormContact()

    return render_to_response('Website/contato.html', locals(), context_instance=RequestContext(request),)

#def login(request):
#    if request.POST.get('username'):
#        user = request.POST.get('username')
#        emailUser = request.POST('username')
#        password = request.POST('password')
#        userAuthenticate = authenticate(username = emailUser, password = password)
#
#        if userAuthenticate is not None:
#            if userAuthenticate.is_active:
#                authlogin(request, userAuthenticate)

@receiver(post_save, sender=User)
def after_save_user( sender, **kwargs ):
    profile = UserProfile.objects.filter( user = kwargs['instance'] )
    if profile.count() == 0:
        UserProfile( user = kwargs['instance'] ).save()

def registerUser(request):
    password = request.POST.get('password')
    #cadastro
    if request.method == 'POST':
        form = userForm(request.POST)
        if form.is_valid():
            newUser = form.save()
            newUser.set_password(password)
            newUser.save()
            return loginUser(request)
    else:
        form = userForm()
    return render_to_response('Website/quiz-login.html', locals(), context_instance=RequestContext(request))


def loginUser(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/quiz-painel')
    if request.method == 'GET' :
        return render_to_response('Website/quiz-login.html', locals(), context_instance=RequestContext(request))

    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)
    #erro=''
    #login
    if user is not None:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect('/quiz-painel')
            #return render_to_response('Website/quiz-painel.html', locals(), context_instance=RequestContext(request))
    else:
        #erro='Dados inválidos!'
        return render_to_response('Website/quiz-login.html', locals(), context_instance=RequestContext(request, {'erro':'Dados Inválidos!'}))

@login_required
def logoutView(request):
    logout(request)
    return HttpResponseRedirect('/')

def search(request):
    from django.db.models.query_utils import Q
    count = 0
    if request.GET['buscap']!='':
        news = News.objects.filter((Q(subTitle__icontains = request.GET['buscap'])| Q(title__icontains = request.GET['buscap'])))
        if news:
            count = news.count()
        c = Context({'itens_busca': news, 'quant':count, 'bus':request.GET['buscap']})
        return render_to_response('Website/noticias.html', locals() ,context_instance=RequestContext(request,c))